package com.cheung.leetcode.greedy;

import org.junit.jupiter.api.Test;

import java.util.stream.IntStream;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.greedy
 * @Author :  cheungming
 * @CreateTime : 2024-06-07 09:24:03
 * @Description : k次取反最大和
 * @Version : 1.0
 */
public class Code1005Test {
    public int largestSumAfterKNegations(int[] nums, int k) {
        // 按绝对值降序排序
        nums = IntStream.of(nums).boxed().sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
                .mapToInt(Integer::intValue).toArray();
        // 前k个负数取反
        for (int i = 0; i < nums.length && k > 0; i++) {
            if (nums[i] < 0) {
                nums[i] = -nums[i];
                k--;
            }
        }
        // 没有k个负数，将最小的正数取反，
        // 这里%2 == 1，说明k是奇数，所以将最小的正数取反，如果是偶数，则不需要取反，因为负负得正后，绝对值不变
        if (k % 2 == 1) {
            nums[nums.length - 1] = -nums[nums.length - 1];
        }

        return IntStream.of(nums).sum();
    }

    @Test
    public void test1() {
        int[] nums = new int[]{4, 2, 3};
        assert largestSumAfterKNegations(nums, 1) == 5;
    }

    @Test
    public void test2() {
        int[] nums = new int[]{3, -1, 0, 2};
        assert largestSumAfterKNegations(nums, 3) == 6;
    }

    @Test
    public void test3() {
        int[] nums = new int[]{2, -3, -1, 5, -4};
        assert largestSumAfterKNegations(nums, 2) == 13;
    }
}
